/**
 * 文件名称 : Pool.java
 * <p>
 * 作者信息 : maidou
 * <p>
 * 创建时间 : 2011-8-4, 上午3:34:28
 * <p>
 * 版权声明 : Copyright (c) 2009-2012 CIeNET Ltd. All rights reserved
 * <p>
 * 评审记录 :
 * <p>
 */

package com.ttomato.game.framework;

import java.util.ArrayList;
import java.util.List;

/**
 * 请在这里增加文件描述
 * <p>
 */
public class Pool<T>
{
    public interface PoolObjectFactory<T>
    {
        public T createObject();
    }
    
    private final List<T> mFreeObjects;
    
    private final PoolObjectFactory<T> mFatctory;
    
    private final int mMaxSize;
    
    public Pool(PoolObjectFactory<T> factory, int maxSize)
    {
        mFatctory = factory;
        mMaxSize = maxSize;
        mFreeObjects = new ArrayList<T>(maxSize);
    }
    
    public T newObject()
    {
        T objcet = null;
        
        if (mFreeObjects.size() == 0)
        {
            objcet = mFatctory.createObject();
        }
        else
        {
            objcet = mFreeObjects.remove(mFreeObjects.size() - 1);
        }
        
        return objcet;
    }
    
    public void free(T object)
    {
        if (mFreeObjects.size() < mMaxSize)
        {
            mFreeObjects.add(object);
        }
    }
}
